package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * 传感器
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/device")
public class DeviceController extends BaseController {
    @Resource
    private DeviceService devicesService;
    @Resource
    private DeviceNodeService deviceNodeService;
    @Resource
    private TerminalTemperatureService terminalTemperatureService;
    @Resource
    private ShopService shopService;
    @Resource
    private PianqusService pianqusService;
    @Resource
    private FeedService feedService;

    @Log("查询设备页面")
    @GetMapping("/{type}")
    @RequiresPermissions("module:device:device")
    String deviceList(Model model,@PathVariable("type") Integer type) {
        if (type != null){
            if (type == 4){
                model.addAttribute("shopType",4);
                model.addAttribute("positionType",1); // 制粒机
            }else if (type == 9){
                model.addAttribute("shopType",9);
                model.addAttribute("positionType",2);// 锅炉
            }else if (type == 10){
                model.addAttribute("shopType",10);
                model.addAttribute("positionType",3); // 油罐
            }else {
                model.addAttribute("shopType",type);
                model.addAttribute("positionType",0);// 防止报错
            }
        }else {
            model.addAttribute("shopType",type);
            model.addAttribute("positionType",0);// 防止报错
        }
        List<Feed> changeFeedList = new ArrayList<>();
        QueryWrapper<Feed> cqw = new QueryWrapper<>();
        cqw.eq("state", 1);
        List<Feed> feeds = feedService.list(cqw);
        Feed feed = new Feed();
        feed.setId(-1);
        feed.setFeedName("清空");
        changeFeedList.add(feed);
        if (feeds != null && feeds.size() > 0){
            changeFeedList.addAll(feeds) ;
        }
        model.addAttribute("changeFeedList",changeFeedList);
        UserDO userDO = getUser();

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(userDO.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", userDO.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);

        if(userDO.getUserType() == 4 ||userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 7){//分厂和 巡检人员

            Shop shop = shopService.findById(userDO.getShopId());
            if(shop != null){
                if(shop.getDeviceShowType() == 0){
                    return "module/device/device";
                }else{
                    model.addAttribute("shopId", userDO.getShopId());
                    model.addAttribute("deviceShowType",1);
                    QueryWrapper<Device> qw1 = new QueryWrapper<>();
                    qw1.eq("shop_id", userDO.getShopId());
                    qw1.last("limit 1");
                    Device device = devicesService.getOne(qw1);
                    if(device != null){
                        model.addAttribute("online_state",device.getOnlineState());
                    }
                    return "module/device/node/node";
                }
            }
        }

        return "module/device/shop";
    }


    @Log("查询设备页面")
    @GetMapping("/yangan")
    @RequiresPermissions("module:device:device")
    String deviceYanGanShopList(Model model) {
        model.addAttribute("shopType", 7);
        UserDO userDO = getUser();

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(userDO.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", userDO.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        return "module/device/yangan/shop";
    }



    @Log("查询设备页面")
    @GetMapping("/ipvoice")
    @RequiresPermissions("module:device:device")
    String deviceIpVoiceShopList(Model model) {
        model.addAttribute("shopType", 11);
        UserDO userDO = getUser();

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(userDO.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", userDO.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        return "module/device/ipvoice/shop";
    }



    @Log("查询设备页面")
    @GetMapping("/yangan/{shopId}")
    @RequiresPermissions("module:device:device")
    String deviceYanGanList(Model model, @PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopType", 7);
        model.addAttribute("shopId", shopId);
        return "module/device/yangan/device";
    }



    @Log("查询设备页面")
    @GetMapping("/ipvoice/{shopId}")
    @RequiresPermissions("module:device:device")
    String deviceIpVoiceList(Model model, @PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopType", 11);
        model.addAttribute("shopId", shopId);
        return "module/device/ipvoice/device";
    }



    @Log("查询设备页面")
    @GetMapping("/edge")
    @RequiresPermissions("module:device:device")
    String deviceEdgeShopList(Model model) {
        model.addAttribute("shopType", 8);
        UserDO userDO = getUser();

        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(userDO.getUserType() > 1) {//集团用户
            qw.eq("jituan_id", userDO.getGroupId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        return "module/device/edge/shop";
    }



    @Log("查询设备页面")
    @GetMapping("/edge/{shopId}")
    @RequiresPermissions("module:device:device")
    String deviceEdgeList(Model model, @PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopType", 4);
        model.addAttribute("shopId", shopId);
        return "module/device/edge/device";
    }


    @Log("查询设备页面")
    @GetMapping("/view/{shopId}/{shopType}")
    @RequiresPermissions("module:device:device")
    String deviceList22(Model model,@PathVariable("shopId") Integer shopId,@PathVariable("shopType") Integer shopType, Integer positionType) {
        model.addAttribute("shopType",shopType);
        model.addAttribute("shopId",shopId);
        if (positionType != null){
            model.addAttribute("positionType",positionType);
        }else {
            model.addAttribute("positionType",0);// 防止报错
        }

        QueryWrapper<Device> qw = new QueryWrapper<>();
        qw.eq("shop_id", shopId);
        long count = devicesService.count(qw);
        model.addAttribute("deviceCount",count);

        return "module/device/device";
    }


    /**
     *  按照分类显示tab菜单列表
     * @param model
     * @param shopId
     * @return
     */
    @Log("查询设备页面")
    @GetMapping("/integration/{shopId}")
//    @RequiresPermissions("module:device:device")
    String integration(Model model,@PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopId",shopId);
        Shop shop = shopService.getDeviceCountByShopId(shopId);
        model.addAttribute("shop",shop);

        List<Map<String,Object>> tabItems = new ArrayList<>();
        if(shop.getDeviceCount2() > 0){
            Map<String, Object> map = new HashMap<>();
            map.put("name","制粒机测温设备");
            map.put("code","device_count_2");
            map.put("count",shop.getDeviceCount2());
            tabItems.add(map);
        }
//
//        if(shop.getDeviceCount3() > 0){
//            Map<String, Object> map1 = new HashMap<>();
//            map1.put("name","制粒机测温电流设备");
//            map1.put("code","device_count_3");
//            map1.put("count",shop.getDeviceCount3());
//            tabItems.add(map1);
//        }
//
        if(shop.getRangeCount0() > 0){
            Map<String, Object> map2 = new HashMap<>();
            map2.put("name","筒仓测量设备");
            map2.put("code","range_count_0");
            map2.put("count",shop.getRangeCount0());
            tabItems.add(map2);
        }

        if(shop.getRangeCount1() > 0){
            Map<String, Object> map3 = new HashMap<>();
            map3.put("name","油罐测量设备");
            map3.put("code","range_count_1");
            map3.put("count",shop.getRangeCount1());
            tabItems.add(map3);
        }

        if(shop.getWeldingCount0() > 0){
            Map<String, Object> map4 = new HashMap<>();
            map4.put("name","电焊机动火设备");
            map4.put("code","welding_count_0");
            map4.put("count",shop.getWeldingCount0());
            tabItems.add(map4);
        }
//
        if(shop.getWeldingCount1() > 0){
            Map<String, Object> map5 = new HashMap<>();
            map5.put("name","等离子动火设备");
            map5.put("code","welding_count_1");
            map5.put("count",shop.getWeldingCount1());
            tabItems.add(map5);
        }


        if(shop.getDeviceGLCount() > 0){
            Map<String, Object> map6 = new HashMap<>();
            map6.put("name","锅炉测温");
            map6.put("code","device_gl_count");
            map6.put("count",shop.getDeviceGLCount());
            tabItems.add(map6);
        }

        if(shop.getDeviceYGCount() > 0){
            Map<String, Object> map7 = new HashMap<>();
            map7.put("name","油罐检测");
            map7.put("code","device_yg_count");
            map7.put("count",shop.getDeviceYGCount());
            tabItems.add(map7);
        }
        model.addAttribute("tabItems",tabItems);
        return "module/device/integration";
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("module:device:device")
    public DataTableLayUI<Device> list(DataTableLayUI<Device> condition) {
        UserDO userDO = getUser();
        Map<String,Object> map = condition.getSearchParams();
        String deviceNum = null;
        if(map != null) {
            deviceNum = StrUtil.isNotEmpty(map.get("search_like_keyword").toString()) ? map.get("search_like_keyword").toString():null;
        }
        Integer shopId = StrUtil.isNotEmpty(map.get("search_eq_shopId").toString()) ? Integer.parseInt(map.get("search_eq_shopId").toString()):null;
        Integer deviceType = map.get("search_eq_deviceType") != null ? Integer.parseInt(map.get("search_eq_deviceType").toString()):null;
        Integer positionType = map.get("search_eq_positionType") != null ? Integer.parseInt(map.get("search_eq_positionType").toString()):null;

        Map<String,Object> map1 = new HashMap<>();
        if(deviceNum != null){
            map1.put("device_num",deviceNum);
        }
        if(deviceType!=null){
            map1.put("device_type",deviceType);
        }
        if(positionType!=null && positionType != 0){
            map1.put("position_type",positionType);
        }

        if(userDO.getUserType() == 2){//集团管理员
            map1.put("group_id",userDO.getGroupId());
        }else if(userDO.getUserType() == 3){//分区管理员
            map1.put("pianqu_id",userDO.getPianquId());
        }else{//分厂和 巡检人员
            map1.put("shop_id",userDO.getShopId());
        }

        if(shopId!=null){
            map1.put("shop_id", shopId);
        }

        Page<Device> page = devicesService.getPage(condition);
        List<Device> list = devicesService.getPageByUserId(page,map1);
        DataTableLayUI<Device> dt = devicesService.pageSearchCustom(page,list,condition);
        List<Device> devices = dt.getData();
        for (Device device : devices){
            Shop shop = shopService.findById(device.getShopId());
            if(shop != null){
                device.setShopName(shop.getShopName());
            }
            QueryWrapper<DeviceNode> deviceNodeQueryWrapper = new QueryWrapper<>();
            deviceNodeQueryWrapper.eq("device_id", device.getId());
            if(positionType!=null && positionType != 0){
                deviceNodeQueryWrapper.eq("position_type",positionType);
            }
            List<DeviceNode> nodeList = deviceNodeService.list(deviceNodeQueryWrapper);
            device.setNodeList(nodeList);
        }
        return dt;
    }

    @Log("单个的图标界面")
    @GetMapping("/charts/{id}")
    String charts(@PathVariable("id") Integer id, Model model) {
        Device device = devicesService.findById(id);
        if(device != null){
            Map<String,Object> mapReturn = terminalTemperatureService.getChartData(id, DateUtils.getDay(),DateUtils.getDay(), null);
            model.addAttribute("charts", mapReturn);
        }
        model.addAttribute("device", device);

        model.addAttribute("begin_date", DateUtils.getDay());
        model.addAttribute("end_date", DateUtils.getDay());
        return "module/device/charts";
    }


    @Log("单个的图标界面数据")
    @PostMapping("/charts/data")
    @ResponseBody
    R chartsData(@RequestParam Map<String,Object> paramJson) {
        int deviceId = Integer.parseInt(paramJson.get("deviceId").toString());
        String beginDate = paramJson.containsKey("begin_date") ? paramJson.get("begin_date").toString() :  DateUtils.getDay();
        String endDate = paramJson.containsKey("end_date") ? paramJson.get("end_date").toString():  DateUtils.getDay();
        Integer positionType = paramJson.containsKey("positionType") ? Integer.parseInt(paramJson.get("positionType").toString()): null;


        Map<String,Object> mapReturn = terminalTemperatureService.getChartData(deviceId,beginDate,endDate, positionType);

        return R.ok(mapReturn);
    }


    @Log("单个的图标界面数据")
    @PostMapping("/shop/device/charts/data")
    @ResponseBody
    R shopDeviceData(@RequestParam Map<String,Object> paramJson) {
        JSONObject jsonObject = JSONUtil.parseObj(paramJson);
        int dateType = jsonObject.containsKey("dateType") ? jsonObject.getInt("dateType") : 0;
        int shopId = jsonObject.containsKey("shopId") && StrUtil.isNotEmpty(jsonObject.getStr("shopId")) ? jsonObject.getInt("shopId") : 0;
        String searchDate = jsonObject.containsKey("searchDate") && StrUtil.isNotEmpty(jsonObject.getStr("searchDate")) ? jsonObject.getStr("searchDate") : "";
        Integer positionType = jsonObject.containsKey("positionType") && StrUtil.isNotEmpty(jsonObject.getStr("positionType")) ? Integer.parseInt(jsonObject.getStr("positionType")) : null;
        Integer feedId = jsonObject.containsKey("feedId") && StrUtil.isNotEmpty(jsonObject.getStr("feedId")) ?    Integer.parseInt(jsonObject.getStr("feedId")) : null;
        String feedIds = jsonObject.containsKey("feedIds") && StrUtil.isNotEmpty(jsonObject.getStr("feedIds")) ?    jsonObject.getStr("feedIds") : null;
        String nodeIds = jsonObject.containsKey("nodeIds") && StrUtil.isNotEmpty(jsonObject.getStr("nodeIds")) ?    jsonObject.getStr("nodeIds") : null;

        UserDO userDO = getUser();
        if(shopId == 0){
            if(userDO.getUserType() == 4 || userDO.getUserType() == 5|| userDO.getUserType() == 6 || userDO.getUserType() == 10){
                shopId = userDO.getShopId();
            }
        }

        Map<String,Object> map = new HashMap<>();
        Map<String,Object> mapReturn2 = terminalTemperatureService.getChartDataByShopDevice(shopId, dateType, 2, searchDate, positionType, feedId,feedIds,nodeIds);
        map.put("all_data_2", mapReturn2);


        Map<String,Object> mapReturn3 = terminalTemperatureService.getChartDataByShopDevice(shopId, dateType, 3, searchDate, positionType, feedId,feedIds,nodeIds);
        map.put("all_data_3", mapReturn3);
        return R.ok(map);
    }


    @Log("新增设备页面")
    @GetMapping("/add/{shopId}")
    @RequiresPermissions("module:device:add")
    String add(Model model,@PathVariable("shopId") Integer shopId) {
        Device device = new Device();
//        device.setDeviceType(deviceType);
        device.setNodeCount(1);
        device.setAddValue(0d);
        device.setSort(0);

        device.setWarnMinValue(80f);
        device.setWarnMaxValue(120f);
        device.setSort(0);
        device.setShopId(shopId);
//        if(deviceType == 2){
//            device.setXishuA(0.038153);
//            device.setXishuB(-24.990462);
//        }else{
//            device.setXishuA(0.381534);
//            device.setXishuB(-249.904617);
//        }

        model.addAttribute("device", device);

        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("state",1);
        List<Shop> shops = shopService.list();
        model.addAttribute("shops", shops);
        return "module/device/detail";
    }

    @Log("新增设备页面")
    @GetMapping("/add/{shopId}/{deviceType}")
    @RequiresPermissions("module:device:add")
    String addByType(Model model,@PathVariable("shopId") Integer shopId,@PathVariable("deviceType") Integer deviceType) {
        Device device = new Device();
//        device.setDeviceType(deviceType);
        device.setNodeCount(1);
        device.setAddValue(0d);
        device.setSort(0);
        device.setDeviceType(deviceType);

        device.setWarnMinValue(80f);
        device.setWarnMaxValue(120f);
        device.setSort(0);
        device.setShopId(shopId);
//        if(deviceType == 2){
//            device.setXishuA(0.038153);
//            device.setXishuB(-24.990462);
//        }else{
//            device.setXishuA(0.381534);
//            device.setXishuB(-249.904617);
//        }

        model.addAttribute("device", device);

//        QueryWrapper<Shop> qw = new QueryWrapper<>();
//        qw.eq("state",1);
//        List<Shop> shops = shopService.list();
//        model.addAttribute("shops", shops);
        if(deviceType == 6){

            QueryWrapper<Device> qwVoice = new QueryWrapper<>();
            qwVoice.eq("shop_id", shopId);
            qwVoice.eq("device_type", 8);
            List<Device> voiceList = devicesService.list(qwVoice);
            model.addAttribute("voiceList", voiceList);

            return "module/device/yangan/detail";
        } else if(deviceType == 7){
            return "module/device/edge/detail";
        } else if(deviceType == 8){
            return "module/device/ipvoice/detail";
        }
        return "module/device/detail";
    }


    @Log("编辑设备页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:device:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        Device device = devicesService.findById(id);
        model.addAttribute("device", device);
        if(device.getDeviceType() == 6){

            QueryWrapper<Device> qwVoice = new QueryWrapper<>();
            qwVoice.eq("shop_id", device.getShopId());
            qwVoice.eq("device_type", 8);
            List<Device> voiceList = devicesService.list(qwVoice);
            model.addAttribute("voiceList", voiceList);

            return "module/device/yangan/detail";
        } else if(device.getDeviceType() == 7){
            return "module/device/edge/detail";
        } else if(device.getDeviceType() == 8){
            return "module/device/ipvoice/detail";
        }


        QueryWrapper<Shop> qw = new QueryWrapper<>();
        qw.eq("state",1);
        List<Shop> shops = shopService.list();
        model.addAttribute("shops", shops);

        return "module/device/detail";
    }

    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:device:add")
    public R save(@Valid Device device) {

        QueryWrapper<Device> qw = new QueryWrapper<>();
        qw.eq("device_num", device.getDeviceNum());
        qw.last("limit 1");
        Device device1 = devicesService.getOne(qw);
        if(device1 != null){
            Shop shop = shopService.findById(device.getShopId());
            return R.error("该设备编号已绑定到 :" + shop.getShopName() +" 企业");
        }

        device.setLastActiveTime(new Date());
        device.setWarningTimeInterval(60);
        if (devicesService.save(device)) {
            if(device.getNodeCount() != null && device.getNodeCount() > 0){
                for (int i = 0;i < device.getNodeCount();i++){
                    DeviceNode deviceNode = new DeviceNode();
                    deviceNode.setTerminalName((i + 1) + "号制粒机");
                    deviceNode.setShopId(device.getShopId());
                    deviceNode.setDeviceId(device.getId());
                    deviceNode.setNodeIndex(1);
//                    deviceNode.setInsIndex(i);
                    deviceNode.setInsIndex(0);
                    deviceNode.setCurrentValue(0d);
                    deviceNode.setPowerState(0);
                    deviceNode.setPositionType(device.getPositionType());
                    deviceNodeService.save(deviceNode);
                }
            }
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log("更新设备")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:device:edit")
    public R update(@Valid Device device) {

        QueryWrapper<Device> qw = new QueryWrapper<>();
        qw.eq("device_num", device.getDeviceNum());
        qw.ne("id", device.getId());
        qw.last("limit 1");
        Device device1 = devicesService.getOne(qw);
        if(device1 != null){
            Shop shop = shopService.findById(device.getShopId());
            return R.error("该设备编号已绑定到 :" + shop.getShopName() +" 企业");
        }

        devicesService.updateById(device);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除设备")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:device:remove")
    public R remove( Integer id) {
        if (devicesService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }
}
